package leetcode.easy.q111;

import leetcode.util.TreeNode;

public class Q {
}

/*
基于solution1优化
思路：当发现存在叶子节点时，另一节点的访问则可以忽略
 */
class Solution2 {
    public int minDepth(TreeNode root) {
        if (root == null) return 0;
        if (isLeaf(root)) {
            return 1;
        }
        return minDep(root);
    }

    private int minDep(TreeNode root) {
        if (isLeaf(root.left)) {
            return 2;
        } else if (isLeaf(root.right)) {
            return 2;
        } else {
            if (root.left == null) {
                return minDep(root.right) + 1;
            } else if (root.right == null) {
                return minDep(root.left) + 1;
            }
            return Math.min(minDep(root.left), minDep(root.right)) + 1;
        }
    }

    private boolean isLeaf(TreeNode node) {
        return node != null && node.left == null && node.right == null;
    }

}

/*
递归访问所有节点，最终确认最小深度
 */
class Solution {
    public int minDepth(TreeNode root) {
        if (root == null) return 0;

        return minDep(root);
    }

    private int minDep(TreeNode root) {
        if (root.left == null && root.right == null) return 1;
        if (root.left == null) {
            return minDep(root.right) + 1;
        } else if (root.right == null) {
            return minDep(root.left) + 1;
        }
        return Math.min(minDep(root.left), minDep(root.right)) + 1;
    }
}